import 'dart:io';
import 'package:cloud_medicine/components/above_loading.dart';
import 'package:cloud_medicine/http/config.dart';
import 'package:cloud_medicine/components/user_avatar.dart';
import 'package:cloud_medicine/components/util.dart';
import 'package:cloud_medicine/http/HttpUtil.dart';
import 'package:cloud_medicine/http/user_api.dart';
import 'package:cloud_medicine/model/detail_user_info.dart';
import 'package:flutter/cupertino.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_picker/image_picker.dart';
import 'package:flutter/material.dart';

class UserPage extends StatefulWidget {
  @override
  _UserPageState createState() => _UserPageState();
}

class _UserPageState extends State<UserPage> {
  bool _loading;
  bool _submitLoading = false;
  String _image;
  String avatar;
  String age;
  int sex;
  List<int> _errorList = [];
  final picker = ImagePicker();
  final TextEditingController nameController = TextEditingController();
  final TextEditingController phoneController = TextEditingController();
  final TextEditingController ageController = TextEditingController();
  final RegExp regAge = RegExp(r"^[0-9]{0,3}$");
  final RegExp regPhone = RegExp(r"^1[0-9]{10}$");
  final RegExp regName = RegExp(r"^[\u4E00-\u9FA5A-Za-z]{0,6}$");
  final String ageErorrText = '年龄必须全由数字组成且不能超过三位数';
  final String phoneErorrText = '手机号必须全由数字组成且必须为11位';
  final String nameErorrText = '姓名只能由中文或英文组成且不能超过6位';
  final TextStyle textStyle = TextStyle(fontSize: 18, color: Colors.grey[600]);
  final TextStyle plactholderStyle = TextStyle(color: Colors.grey[500]);
  static const double imageStyle = 120;

  @override
  void initState() {
    super.initState();
    _loadData();
  }

  // 加载数据
  Future<Null> _loadData() async {
    setState(() {
      _loading = true;
    });
    dynamic res = await getDetailUserInfo_api('$backIP/user/userInfo', {});
    DetailUserInfo detailUserInfo = DetailUserInfo.init(res['data']);
    if (mounted) {
      setState(() {
        avatar = detailUserInfo.avatar;
        sex = detailUserInfo.sex;
        nameController.text = detailUserInfo.realname;
        phoneController.text = detailUserInfo.phoneNumber;
        ageController.text = detailUserInfo.age;
        _loading = false;
      });
    }
  }

  Future getImage(bool isTakePhoto) async {
    Navigator.pop(context);
    final pickedFile = await picker.getImage(
        source: isTakePhoto ? ImageSource.camera : ImageSource.gallery);

    showDialog(
        context: context,
        builder: (context) {
          return new AboveLoading(
            content: '上传中...',
          );
        });
    upLoadImage(File(pickedFile.path), (imageUrl) {
      setState(() {
        _image = imageUrl;
      });
      Navigator.pop(context);
    });
  }

  setImage(String imageUrl) {
    setState(() {
      avatar = imageUrl;
    });
  }

  verifyInput(int index, String text, String errorText) {
    if (text == '') {
      return '输入不能为空';
    }

    return _errorList.contains(index) ? errorText : null;
  }

  Widget _getInputTextField(
    String title,
    TextEditingController controller,
    String placeholder,
    int index, {
    String errorText,
    RegExp reg,
  }) {
    return Container(
      padding: EdgeInsets.all(10),
      margin: EdgeInsets.only(top: 20),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border.all(color: Colors.grey[300], width: 1),
      ),
      child: Row(
        children: <Widget>[
          Container(
            width: 80,
            child: Text('$title', style: textStyle),
          ),
          Expanded(
            child: TextField(
              controller: controller,
              maxLines: 1,
              decoration: InputDecoration(
                errorText: verifyInput(index, controller.text, errorText),
                contentPadding: EdgeInsets.symmetric(vertical: 10.0),
                border: OutlineInputBorder(
                  borderSide: BorderSide.none,
                ),
                hintText: placeholder,
                hintStyle: plactholderStyle,
              ),
              onChanged: (String text) {
                if (!(reg.hasMatch(text))) {
                  if (!_errorList.contains(index)) {
                    setState(() {
                      _errorList.add(index);
                    });
                  }
                } else {
                  setState(() {
                    _errorList.remove(index);
                  });
                }
              },
            ),
          ),
        ],
      ),
    );
  }

  Widget _getRadio(int radioValue) {
    return Radio(
      value: radioValue,
      groupValue: sex,
      onChanged: (value) {
        setState(() {
          sex = value;
        });
      },
    );
  }

  // 提交数据
  Future<Null> _submitData() async {
    if (nameController.text == '' ||
        ageController.text == '' ||
        phoneController.text == '') {
      Fluttertoast.showToast(
        msg: '填入的信息不符合规范，请检查',
        gravity: ToastGravity.CENTER,
        backgroundColor: Colors.red,
        textColor: Colors.white,
      );
      return;
    }
    if (_errorList.length != 0) {
      Fluttertoast.showToast(
        msg: '填入的密码有 ${_errorList.length}项 不符合规范，请修改之后再重试',
        gravity: ToastGravity.CENTER,
        backgroundColor: Colors.red,
        textColor: Colors.white,
      );
      return;
    }
    setState(() {
      _submitLoading = true;
    });
    print(_errorList);
    if (mounted) {
      dynamic res = await alterUserInfo_api('$backIP/user/userInfo', {
        'name': nameController.text,
        'sex': sex,
        'phonenumber': phoneController.text,
        'age': ageController.text
      });
      await getBasicUserInfo_api(); // 重新获取当前用户基本信息
      setState(() {
        _submitLoading = false;
      });
      Navigator.pop(context);
      Fluttertoast.showToast(
        msg: '修改信息成功',
        gravity: ToastGravity.TOP,
        backgroundColor: Colors.green,
        textColor: Colors.white,
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[200],
      appBar: AppBar(
        title: Text('用户信息显示'),
        centerTitle: true,
      ),
      body: _loading
          ? loadingWidget(_loading)
          : Container(
              child: SingleChildScrollView(
                child: Container(
                  height: MediaQuery.of(context).size.height - 80,
                  child: ListView(
                    shrinkWrap: true,
                    children: <Widget>[
                      SizedBox(height: 20),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        children: <Widget>[
                          _image == null
                              ? UserAvatar(
                                  avatar: avatar,
                                  imageStyle: imageStyle,
                                )
                              : Container(
                                  width: imageStyle,
                                  height: imageStyle,
                                  child: ClipRRect(
                                    borderRadius:
                                        BorderRadius.circular(imageStyle / 2),
                                    child: Image.network(_image),
                                  ),
                                ),
                        ],
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          RaisedButton(
                            textColor: Colors.white,
                            color: Colors.blue,
                            onPressed: () {
                              _image == null ? pickImage() : uploadAvatar();
                            },
                            child: Text(_image == null ? '上传图片' : '修改头像'),
                          ),
                        ],
                      ),
                      _getInputTextField(
                        '姓名',
                        nameController,
                        '请输入你的姓名',
                        0,
                        errorText: nameErorrText,
                        reg: regName,
                      ),
                      Container(
                        padding: EdgeInsets.all(10),
                        margin: EdgeInsets.only(top: 20),
                        decoration: BoxDecoration(
                          color: Colors.white,
                          border: Border.all(color: Colors.grey[300], width: 1),
                        ),
                        child: Row(
                          children: <Widget>[
                            Container(
                              width: 80,
                              child: Text('性别', style: textStyle),
                            ),
                            Expanded(
                                child: Row(
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: <Widget>[
                                _getRadio(0),
                                Text("男"),
                                SizedBox(width: 20),
                                _getRadio(1),
                                Text("女"),
                              ],
                            )),
                          ],
                        ),
                      ),
                      _getInputTextField(
                        '年龄',
                        ageController,
                        '请输入年龄',
                        1,
                        errorText: ageErorrText,
                        reg: regAge,
                      ),
                      _getInputTextField(
                        '手机号',
                        phoneController,
                        '请输入11位手机号',
                        2,
                        errorText: phoneErorrText,
                        reg: regPhone,
                      ),
                      SizedBox(height: 20),
                      Flex(
                        direction: Axis.vertical,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          RaisedButton(
                            child: Text(_submitLoading ? '保存中...' : '保存'),
                            color: Colors.blueAccent,
                            textColor: Colors.white,
                            onPressed: () {
                              if (_submitLoading) {
                                Fluttertoast.showToast(
                                  msg: '请勿重复点击',
                                  backgroundColor: Colors.black,
                                  textColor: Colors.white,
                                );
                                return;
                              }
                              _submitData();
                            },
                          ),
                        ],
                      ),
                      SizedBox(height: 20),
                    ],
                  ),
                ),
              ),
            ),
    );
  }

  // 修改头像，在此之前上传头像
  uploadAvatar() async {
    dynamic res =
        await alterAvatar_api('$backIP/user/avatar', {'avatar': _image});
    await getBasicUserInfo_api();
    res['code'] == 0
        ? successToast(res['message'])
        : errorToast(res['message']);
    setState(() {
      avatar = _image;
      _image = null;
    });
  }

  pickImage() {
    showModalBottomSheet(
      context: context,
      builder: (context) => Container(
        height: 120,
        child: Column(
          children: <Widget>[_item('拍照', true), _item('从相册选择', false)],
        ),
      ),
    );
  }

  _item(String title, bool isTakePhoto) {
    return GestureDetector(
      child: ListTile(
        leading: Icon(isTakePhoto ? Icons.camera_alt : Icons.photo_library),
        title: Text(title),
        onTap: () => getImage(isTakePhoto),
      ),
    );
  }
}
